package calculator.main;

import java.io.Console;

import javapop.framework.ParseInput;
import javapop.framework.ParseResult;
import javapop.framework.input.StringParseInput;
import calculator.ast.Expr;
import calculator.parser.CalculatorGrammar;

public class ConsoleMain {

	public static void main(String...args) {
		Console console = System.console();
		if(console==null) {
			System.err.println("No console available => abort\n");
			System.exit(1);
		}
		
		console.printf("Calculator (C) 2009 F. Peschanski\n");
		
		CalculatorGrammar calc = new CalculatorGrammar();
		
		String cmd = null;
		boolean finish = false;
		
		while(!finish) {
			console.printf("> ");
			cmd = console.readLine();
			if(cmd.equals("quit")) {
				console.printf("Good bye\n");
				finish = true;
				continue;
			}
			ParseInput input = new StringParseInput(cmd);
			ParseResult<Expr> expr = calc.parse(input);
			if(expr.isError()) {
				console.printf("Error: %s\n",expr.asError().getErrorMessage());
				console.printf("==> %s\n",input.thisLine());
			} else {				
				try {
					double val = expr.getResult().eval();
					console.printf("%s\n",""+val);
				} catch(Error e) {
					console.printf("Error: cannot evaluate\n  ==> %s\n",expr.toString());
				}
			}
		}
	}
}
